﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Liquid.Collections;
using System.ComponentModel;

namespace NNote.DocumentModel {
	public class Document : Component {
		public static Document FromFile(string filename) {
			return new Document {
				Filename = filename
			};
		}

		public Document() {
			this.Filename = null;
		}

		public string Filename {
			get { return m_Filename; }
			private set {
				m_Filename = value;
				if (value == null) {
					Title = "Untitled";
				} else {
					Title = Path.GetFileName(value);
				}
			}
		}
		private string m_Filename;

		public string Title {
			get { return m_Title; }
			set {
				if (m_Title != value) {
					m_Title = value;
					OnTitleChanged(EventArgs.Empty);
				}
			}
		}
		string m_Title;
		private static readonly object EventTitleChanged = new object();
		public event EventHandler TitleChanged {
			add { Events[EventTitleChanged] = Delegate.Combine(Events[EventTitleChanged], value); }
			remove { Events[EventTitleChanged] = Delegate.Remove(Events[EventTitleChanged], value); }
		}
		protected void OnTitleChanged(EventArgs e) {
			var handler = (EventHandler)Events[EventTitleChanged];
			if (handler != null)
				handler(this, e);
		}

		public bool Modified {
			get { return m_Modified; }
			set {
				if (m_Modified != value) {
					m_Modified = value;
					OnModifiedChanged(EventArgs.Empty);
					if (Viewer != null)
						Viewer.Modified = value;
				}
			}
		}
		bool m_Modified;
		private static readonly object EventModifiedChanged = new object();
		public event EventHandler ModifiedChanged {
			add { Events[EventModifiedChanged] = Delegate.Combine(Events[EventModifiedChanged], value); }
			remove { Events[EventModifiedChanged] = Delegate.Remove(Events[EventModifiedChanged], value); }
		}
		protected void OnModifiedChanged(EventArgs e) {
			var handler = (EventHandler)Events[EventModifiedChanged];
			if (handler != null)
				handler(this, e);
		}

		public IDocumentViewer Viewer { get; internal set; }

		public void Save() {
			Viewer.Save(Filename);
		}
		public void SaveAs(string filename) {
			this.Filename = filename;
			Save();
		}
	}
}
